﻿using System.Collections.Generic;
using System.Linq;
using System.Printing;
using System.Management;
using System.Net;

namespace Coding4Fun.PrinterDisplayHack
{
    public class LocalPrinter
    {
        public string Name { get; set; }
        public string PortName { get; set; }
        public IPAddress Address { get; set; }
    }

    public class PrinterUtils
    {
        static public List<LocalPrinter> GetPrinters()
        {
            Dictionary<string, IPAddress> ports = GetPrinterPorts();

            EnumeratedPrintQueueTypes[] enumerationFlags = { EnumeratedPrintQueueTypes.Local };

            LocalPrintServer printServer = new LocalPrintServer();

            PrintQueueCollection printQueuesOnLocalServer = printServer.GetPrintQueues(enumerationFlags);

            return (from printer in printQueuesOnLocalServer
                    where ports.ContainsKey(printer.QueuePort.Name)
                    select new LocalPrinter()
                               {
                                   Name = printer.Name, 
                                   PortName = printer.QueuePort.Name, 
                                   Address = ports[printer.QueuePort.Name]
                               }).ToList();
        }

        static public Dictionary<string, IPAddress> GetPrinterPorts()
        {
            var ports = new Dictionary<string, IPAddress>();

            ObjectQuery oquery = new ObjectQuery("Select Name, HostAddress from Win32_TCPIPPrinterPort where PortNumber = 9100");

            ManagementObjectSearcher mosearcher = new ManagementObjectSearcher(oquery);

            using (var searcher = new ManagementObjectSearcher(oquery))
            {
                var objectCollection = searcher.Get();

                foreach (ManagementObject managementObjectCollection in objectCollection)
                {
                    var portAddress = IPAddress.Parse(managementObjectCollection.GetPropertyValue("HostAddress").ToString());
                    ports.Add(managementObjectCollection.GetPropertyValue("Name").ToString(), portAddress);
                }
            }

            return ports;
        }
    }
}
